﻿using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;

namespace FieldDevice
{
    public class StaticLibrary
    {

        /// <summary>
        /// 将一个32位 float转换为一个4字节byte数组
        /// </summary>
        /// <param name="f"></param>
        /// <returns></returns>
        public static byte[] FloatToBytes(float f)
        {
            byte[] bytes = new byte[4];
            float[] floats = new float[1];
            floats[0] = f;
            IntPtr structPtr = Marshal.AllocHGlobal(4);
            Marshal.StructureToPtr(f, structPtr, false);
            Marshal.Copy(floats, 0, structPtr, 1);
            Marshal.Copy(structPtr, bytes, 0, 4);
            return bytes;
        }
        public static void FloatToBytes(float f, byte[] bytes, int begin)
        {
            float[] floats = new float[1];
            floats[0] = f;
            IntPtr structPtr = Marshal.AllocHGlobal(4);
            Marshal.StructureToPtr(f, structPtr, false);
            Marshal.Copy(floats, 0, structPtr, 1);
            Marshal.Copy(structPtr, bytes, begin, 4);
        }
        struct floatstruct
        {
            public float f;
        }
        public static float BytesToFloat(byte[] bytes, int begin)
        {
            IntPtr structPtr = Marshal.AllocHGlobal(4);
            //Marshal.Copy(bytes, begin, structPtr, 4);
            ////Marshal.Copy(structPtr, floats, 0, 1);
            //floatstruct f = (floatstruct)Marshal.PtrToStructure(structPtr, typeof(floatstruct));
            ////FloatToBytes(239.0f, endian, 0);
            byte[] endian = new byte[4];
            endian[0] = bytes[begin + 3];
            endian[1] = bytes[begin + 2];
            endian[2] = bytes[begin + 1];
            endian[3] = bytes[begin + 0];
            Marshal.Copy(endian, 0, structPtr, 4);
            floatstruct f2 = (floatstruct)Marshal.PtrToStructure(structPtr, typeof(floatstruct));
            return f2.f;
        }
        public static short Bytes2Short(byte h, byte l)
        {
            short r = (short)(((short)h) << 8);
            r += (short)l;
            return r;
        }
    }
}
